package com.rms.hkpc.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.rms.hkpc.R;
import com.rms.hkpc.constant.AllConstants;
import com.rms.hkpc.db.dto.PushDto;
import com.rms.hkpc.db.dto.WorksOrderDto;
import com.rms.hkpc.receiver.NotificationReceiver;
import com.rms.hkpc.signalr.SignalRChannel;
import com.rms.hkpc.signalr.SignalRCode;
import com.rms.hkpc.util.DateUtil;
import com.rms.hkpc.util.GsonUtil;
import com.rms.hkpc.util.NotificationUtil;
import com.rms.hkpc.util.OKHttpUtil;

import java.util.Calendar;

public class SignalRService extends Service {
    private final static String HUB_URL = OKHttpUtil.NET_URL + "/api/broadcastHub";
    private final static long sleep = 4000;
    private boolean isRunning = true;
    private SignalRChannel signalRChannel;
    private int i = 0;
    private Thread thread;
    private PowerManager.WakeLock wakeLock;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SignalRCode.RECEIVE_NUM:
                    String json = msg.obj.toString();
                    PushDto<WorksOrderDto> pushDto = (PushDto<WorksOrderDto>) GsonUtil.getInstance().fromJson(json, PushDto.class);
                    showNotification(pushDto);
                    break;
                case SignalRCode.RESULT_NUM:
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(AllConstants.TAG, "service onStartCommand");
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "hkpc:CPUKeepRunning");
            wakeLock.setReferenceCounted(true);
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            int hour = c.get(Calendar.HOUR_OF_DAY);
            if (hour >= 23 || hour <= 6) {
                wakeLock.acquire(5000);
            } else {
                wakeLock.acquire(300000);
            }
        }
        if (signalRChannel == null) {
            signalRChannel = new SignalRChannel(HUB_URL, handler);
            signalRChannel.startConnect();
        }
        if (thread == null) {
            thread = new Thread(runnableSend);
            thread.start();
        }
        return START_STICKY;
    }

    private Runnable runnableSend = new Runnable() {
        @Override
        public void run() {
            while (isRunning) {
                // 刷新连接状态
                if (signalRChannel != null && signalRChannel.isConnected() != true) {
                    signalRChannel.startSync();
                }
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onDestroy() {
        if (wakeLock != null) {
            if (wakeLock.isHeld()) {
                wakeLock.release();
                wakeLock = null;
            }
        }
        if (signalRChannel != null) {
            signalRChannel.stopConnect();
            signalRChannel = null;
        }
        if (thread != null) {
            isRunning = false;
            thread.interrupt();
        }
        Log.i(AllConstants.TAG, "service onDestroy");
        super.onDestroy();
    }

    /**
     * 发送通知
     */
    private void showNotification(PushDto<WorksOrderDto> pushDto) {
        String title = getString(R.string.work_order_notify);
        title = pushDto.getPushAt() == null ? title : title + "   [" + DateUtil.getInstance().DateTimeToStr(pushDto.getPushAt(), "yyyy-MM-dd HH:mm") + "]";
        String info = pushDto.getInfo() == null ? "" : pushDto.getInfo();
        i++;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationUtil.getInstance().getNotificationManager().createNotificationChannel(NotificationUtil.getInstance().getChannel(true));
            Notification.Builder builder = NotificationUtil.getInstance().getNotification(this, true)
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.ic_work_order)
                    .setContentIntent(createIntent(i))
                    .setCustomContentView(getNotificationView(title, info))
                    .setCustomBigContentView(getNotificationBigView(title, info));
            NotificationUtil.getInstance().getNotificationManager().notify(i, builder.build());
        } else {
            NotificationCompat.Builder builder = NotificationUtil.getInstance().getNotificationCompat(this, true)
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.ic_work_order)
                    .setContentIntent(createIntent(i))
                    .setCustomContentView(getNotificationView(title, info))
                    .setCustomBigContentView(getNotificationBigView(title, info));
            NotificationUtil.getInstance().getNotificationManager().notify(i, builder.build());
        }
    }

    /**
     * 获取自定义的通知
     *
     * @return
     */
    private RemoteViews getNotificationView(String title, String info) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_item);
        setTextViewText(remoteViews, title, info);
        return remoteViews;
    }

    /**
     * 获取自定义的通知
     *
     * @return
     */
    private RemoteViews getNotificationBigView(String title, String info) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_big_item);
        setTextViewText(remoteViews, title, info);
        return remoteViews;
    }

    private void setTextViewText(RemoteViews remoteViews, String title, String info) {
        remoteViews.setTextViewText(R.id.tv_title, title);
        remoteViews.setTextViewText(R.id.tv_content, info);
    }


    /**
     * 发送广播
     *
     * @return
     */
    private PendingIntent createIntent(int num) {
        Intent intent = new Intent(this, NotificationReceiver.class);
        return PendingIntent.getBroadcast(this, num, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }
}
